<?php

namespace App\Service;
use App\Service\UserService;
use App\Service\CommService;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Annotation\CachePut;
use Hyperf\DbConnection\Db;

use Monolog\Handler\IFTTTHandler;
use function _PHPStan_b8e553790\RingCentral\Psr7\str;

class PlayletService extends CommicService
{
    private UserService $userService;
    private CommService $commService;


    public function __construct(UserService $userService,CommService $commService)
    {
        parent::__construct();
        $this->userService = $userService;
//        $this->commService = $commService;
//        $container = ApplicationContext::getContainer();
//        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
    }
    public function get_playlet_id($applet_id,$xc_open_id,$playlet_id=0) {
//        拿推广链接的剧id
        #############################################
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        if($playlet_id == 0 ) {
            $spread_id = !empty($open_id_info['spread_id']) ? $open_id_info['spread_id'] : 0;
            $data_spread = DB::table('data_spread')->where('id',$spread_id)->select('playlet_id')->first();
            $playlet_id = isset($data_spread->playlet_id) ? $data_spread->playlet_id : 0;
        }
        #############################################

//       替换用户购买过的合并剧集
        #拿到合并主剧id
        $merge_main_playlet_id = $this->get_merge_main_playlet_id($playlet_id);
        if($merge_main_playlet_id) {
            $user_id = $open_id_info['id'];
            $user_id = "$user_id";
            #获取是否购买过合并剧且主剧id一致的
            $user_same_main_merge_playlet_id =  $this->get_user_same_main_merge_playlet_id($merge_main_playlet_id,$user_id,$applet_id);
            if($user_same_main_merge_playlet_id != false) {
                $playlet_id = $user_same_main_merge_playlet_id;
            }
        }
        return $playlet_id;
    }
    public  function  view_records_add($applet_id,$user_id,$playlet_id,$playlet_number) {
        $redis_key = 'records_wx';
        $insert = [
            'applet_id'=>$applet_id,
            'user_id'=>$user_id,
            'playlet_id'=>$playlet_id,
            'playlet_number'=>$playlet_number,
            'create_time'=>time()
        ];
        $this->redisService->rPush($redis_key,json_encode($insert));
    }
    public function get_recommend($applet_id){
        # 推荐短剧的
        $recommend_info = Db::table("data_playlet_recommend")->where(["applet_id"=>$applet_id,"status"=>1,"stype"=>1])->select("playlet_ids")->first();
        $recommend_info_rec = $this->object_to_find_array($recommend_info);
        if (empty($recommend_info_rec)){
            $recommend_info = Db::table("data_playlet_recommend")->where(["applet_id"=>0,"status"=>1,"stype"=>1])->select("playlet_ids")->first();
        }
        $playlet_ids = explode(',',$recommend_info->playlet_ids);
        if (empty($playlet_ids)){
            return [];
        }else{
            # 获取短剧详情
            $playlet_list = Db::table("playlet")->whereIn("id",$playlet_ids)->select("id as playlet_id","name","tag","introduction","last_episode_number")->get();
            $playlet_list = $this->object_to_array($playlet_list);
            $recd_data_tmp = [];
            $recd_data = [];
            if ($playlet_list){
                foreach ($playlet_list as $key => $value){
                    $value["id"] = $key+1;
                    $value["playlet_number"] = "1";
                    $recd_data_tmp[$value["playlet_id"]] = $value;
                }
                foreach ($playlet_ids as $key=>$val){
                    $recd_data[$key] = $recd_data_tmp[$val];
                }
            }
            return $recd_data;
        }
    }

    public function get_user_recommend($applet_id,$user_id){
        $recd_data = $this->get_recommend($applet_id);
        foreach ($recd_data as $key=>$val){
            $recd_data[$key]["episodes_list"] = $this->get_user_episodes_info($applet_id,$user_id,$val["playlet_id"],(string)$val["playlet_number"]);
            unset($recd_data[$key]["playlet_number"]);
        }
        return $recd_data;
    }

    public function get_user_chasing_list($applet_id,$user_id){
        #追剧列表
        $user_id = (string)$user_id;
        $redis_key = "log:playlet:chasing:".$applet_id;
        $playlet_log_list = $this->redisService->hGet($redis_key,$user_id);
        $playlet_log_list = json_decode($playlet_log_list,true);
        if (empty($playlet_log_list)){
            #购买用户短剧列表
            $playlet_log_list_tmp = Db::table("data_user_chasing_playlet")->where([
                "applet_id"=>$applet_id,
                "user_id"=>$user_id,
            ])->select("playlet_id")->get();
            $playlet_log_list_tmp = $this->object_to_array($playlet_log_list_tmp);
            if (!empty($playlet_log_list_tmp)){
                foreach ($playlet_log_list_tmp as $key =>$value){
                    $playlet_log_list[$key] = $value['playlet_id'];
                }
                $this->redisService->hSet($redis_key,$user_id,json_encode($playlet_log_list));
            }else{
                $playlet_log_list = [];
            }
        }
        return $playlet_log_list;
    }
    public function get_user_recommend_zl_list($applet_id,$user_id){
        $recommend_list = $this->get_user_recommend($applet_id,$user_id);
        $user_chasing_list = $this->get_user_chasing_list($applet_id,$user_id);
        $list = [];
        foreach ($recommend_list as $key=>$value){
            $sval["is_chasing_playlet"] = 0;
            $sval["is_likes"] = 0;
            $likes_ids = $this->get_user_likes($applet_id,$user_id,$value["playlet_id"]);
            if (in_array($value["episodes_list"]["playlet_number"],$likes_ids)){
                $sval["is_likes"] = 1;
            }
            if (in_array($value["playlet_id"],$user_chasing_list)){
                $sval["is_chasing_playlet"] = 1;
            }
            $list[$key] = $sval;
            unset($likes_ids);
        }
        unset($user_chasing_list);
        unset($recommend_list);
        return $list;
    }
    public function get_playlet_info($playlet_id){
        $redis_key = "playlet_info:".$playlet_id;
        $playlet_info =  $this->redisService->get($redis_key);
        $playlet_info = json_decode($playlet_info,true);
        if(empty($playlet_info)) {
            $playlet_info = Db::table("playlet")->where(["id"=>$playlet_id])->select("name","cover","merge_playlet_id","playlet_type","drama_id","main_playlet_id","we_com_cover")->first();
            if(!empty($playlet_info)) {
                $playlet_info = json_decode(json_encode($playlet_info),true);
                $this->redisService->set($redis_key,json_encode($playlet_info));
                $this->redisService->expire($redis_key,300);
            }
        }
        return $playlet_info;
    }
    #获取合并主剧id,有就返回合并id,没有就返回false
    public function get_merge_main_playlet_id($playlet_id) {
        $playlet_info = $this->get_playlet_info($playlet_id);
        if(!empty($playlet_info)) {
            if($playlet_info['playlet_type'] == 2){
                $res = explode(',',$playlet_info['merge_playlet_id']);
                return $res[0];
            }else{
                return $playlet_id;
            }
        } else {
            return false;
        }
    }
    public function get_user_same_main_merge_playlet_id($playlet_id,$user_id,$applet_id=0) {
        #处理合并剧,返回新的剧集id
        #从redis has获取
        #key=key+主剧的id
        #haskey = 用户id
        $user_id = "$user_id";
        //20240325 bobo, 逻辑修改，key添加区分小程序 //先查询新key,找不到新key后再查询旧key
        $merge_playlet_redis_key = 'merge_main_playlet:'.$applet_id.':'.$playlet_id;
        $playletResult =  $this->redisService->hGet($merge_playlet_redis_key,$user_id);
        if($playletResult) {
            return $playletResult;
        }else{
            $redis_key = 'merge_playlet:'.$playlet_id;
            $res =  $this->redisService->hGet($redis_key,$user_id);
            if($res) {
                return $res;
            } else {
                return false;
            }
        }
    }

//    #[Cacheable(prefix: "playlet:episodes_list:",ttl: 7200)]
    public function episodes_list($playlet_id,$spread_id,$merge_main_playlet_id=0){
        $redis_key = 'episodes_list'.$playlet_id.$spread_id;
        $episodes_list = $this->redisService->get($redis_key);
        $episodes_list = json_decode($episodes_list);

        if(empty($episodes_list)) {
            $num = 0;
            $pay = 0;
            //2024-03-04 企业微信图片
            $we_com_cover = '';
            # 剧集列表
            $episodes_list = Db::table("playlet_episodes")->where(["playlet_id"=>$playlet_id])->where('status',1)->orderBy("playlet_number","asc")->select("playlet_id","playlet_number","playlet_number_name","cover","amount","likes_number","share_number","wx_original_time","wx_original_url")->get();
            $playlet = Db::table("playlet")->where(["id"=>$playlet_id])->select(["name","we_com_cover"])->first();
            if($spread_id) {
                $data_spread = DB::table('data_spread')->where('id',$spread_id)->first();
                if(isset($data_spread->playlet_id) && $data_spread->playlet_id == $playlet_id) {
                    $num = $data_spread->playlet_number_num >=1?$data_spread->playlet_number_num :0;
                    $pay = $data_spread->playlet_number_num_pay>0?$data_spread->playlet_number_num_pay:0;
                }
                //2024-03-04 企业微信绑定推广链接上的短剧，如果是相同的剧才会返回对应的企业微信图片
                if($data_spread->playlet_id == $playlet_id){
                    $we_com_cover = $playlet->we_com_cover;
                }

            }
            foreach ($episodes_list as $key=>$value){
                #卡点
                if($num>0&& $pay>0) {
                    if( $value->playlet_number>= $num) {
                        $value->amount = $pay;
                    } else{
                        $value->amount = 0;
                    }
                }
                $value->share_number  = $this->numbers_to_wang(mt_rand(15000,999999));
                $value->name  = $playlet->name;
                //2024-03-04 企业微信图片
                $value->we_com_cover  = $we_com_cover;
                $episodes_list[$key]->name  = $playlet->name;
                $episodes_list[$key]->merge_main_playlet_id  = $merge_main_playlet_id;
                $value->likes_number  = $this->numbers_to_wang(mt_rand(11000,99999));
//            $value->play_url = $this->get_curl_tool($value->play_url);
            }
            $this->redisService->set($redis_key,json_encode($episodes_list));
            $this->redisService->expire($redis_key,300);
        }
        return $episodes_list;

    }

//    #[CachePut(prefix: "playlet:episodes_list:",ttl: 7200)]
    public function update_episodes_list($playlet_id){
        # 更新剧集列表
        $episodes_list = Db::table("playlet_episodes")->where(["playlet_id"=>$playlet_id])->orderBy("playlet_number","asc")->select("playlet_id","playlet_number","playlet_number_name","cover","amount")->get();
        foreach ($episodes_list as $key=>$value){
            $value->cover = $this->get_curl_tool($value->cover);
            $value->share_number  = $this->numbers_to_wang(mt_rand(15000,999999));
            $value->likes_number  = $this->numbers_to_wang(mt_rand(11000,99999));
            $value->play_url = $this->get_curl_tool($value->play_url);
        }
        return $episodes_list;
    }
    public function set_merge_playlet_id($playlet_id,$user_id,$applet_id){
        $user_id = "$user_id";
        $merge_main_playlet_id = $this->get_merge_main_playlet_id($playlet_id);
        //$redis_key = 'merge_playlet:'.$merge_main_playlet_id;
        //20240325 bobo, 逻辑修改，key添加区分小程序
        $redis_key = 'merge_main_playlet:'.$applet_id.':'.$merge_main_playlet_id;
        if($merge_main_playlet_id) {
            $isset_merge_playlet_id = $this->redisService->hGet($redis_key,$user_id);
            if(!$isset_merge_playlet_id)  {
                $this->redisService->hSet($redis_key,$user_id,$playlet_id);
            }
        }
    }
    public function episodes_info($playlet_id,$playlet_number,$fleg = 0){
        $episodes_info = [];
        $redis_key = "playlet:episodes:info:".$playlet_id;
        if ($fleg==0){
            $episodes_info = $this->redisService->hGet($redis_key,$playlet_number);
            $episodes_info = json_decode($episodes_info,true);
        }
        if (empty($episodes_info)){
            $episodes_info = Db::table("playlet_episodes")->where([
                "playlet_id"=> $playlet_id,
                "playlet_number"=> $playlet_number,
            ])->first();
            $episodes_info = $this->object_to_find_array($episodes_info);
            if ($episodes_info){
                unset($episodes_info["id"]);
                $episodes_info["cover"] = $this->get_curl_tool($episodes_info["cover"]);
                $episodes_info["play_url"] = $this->get_curl_tool($episodes_info["play_url"]);
                $this->redisService->hSet($redis_key,$playlet_number,json_encode($episodes_info));
            }
        }
        return $episodes_info;
    }

//    public function  get_faset_info($playlet_id,$playlet_number){
//        $playlet_number = (string)$playlet_number;
//        $redis_key = "playlet:episodes:infos_tmp".$playlet_id;
//        $faset_info = $this->redisService->hGet($redis_key,$playlet_number);
//        $faset_info = json_decode($faset_info,true);
//        if (empty($faset_info)){
//            $episodes_list = $this->episodes_list($playlet_id);
//            $faset_info = $this->object_to_find_array($episodes_list[$playlet_number-1]);
//            $this->redisService->hSet($redis_key,$playlet_number,json_encode($faset_info));
//        }
//        return $faset_info;
//    }
    public function  get_faset_info($playlet_id,$playlet_number){
        $playlet_number = (string)$playlet_number;
        $episodes_list = $this->episodes_list($playlet_id,0);
        $faset_info = $this->object_to_find_array($episodes_list[$playlet_number-1]);
        return $faset_info;
    }
    public function playlet_info($playlet_id,$fleg = 0){
        $playlet_id = (string)$playlet_id;
        # 短剧详情
        $playlet_info = [];
        $redis_key = "playlet:info";
        if ($fleg==0){
            $playlet_info = $this->redisService->hGet($redis_key,$playlet_id);
            $playlet_info = json_decode($playlet_info,true);
        }
        if (empty($episodes_info)){
            $playlet_info = Db::table("playlet")->where([
                "id"=> $playlet_id,
            ])->first();
            $playlet_info = $this->object_to_find_array($playlet_info);
            if ($playlet_info){
                $playlet_info["cover"] = $this->get_curl_tool($playlet_info["cover"]);
                $this->redisService->hSet($redis_key,$playlet_id,json_encode($playlet_info));
            }
        }
        return $playlet_info;
    }
    public function get_user_episodes_info($user_id,$applet_id,$playlet_id,$playlet_number){
        $episodes_info = $this->get_faset_info($playlet_id,$playlet_number);
        $is_likes = 1;
        $is_chasing_playlet = 1;
        if ($playlet_number > 2){
            $is_likes = 0;
            $is_chasing_playlet = 0;
        }
        unset($episodes_info["create_at"]);
        $episodes_info["is_chasing_playlet"] = $is_chasing_playlet;
        $episodes_info["is_likes"] = $is_likes;
        $episodes_info["pay_staus"] = 1;
        return $episodes_info;
    }

    public function get_episodes_info($user_id,$applet_id,$playlet_id,$playlet_number){


        $episodes_info = $this->episodes_info($playlet_id,$playlet_number);
        $is_likes = 1;
        $is_chasing_playlet = 1;
        if ($playlet_number > 2){
            $is_likes = 0;
            $is_chasing_playlet = 0;
        }
        unset($episodes_info["create_at"]);
        $episodes_info["is_chasing_playlet"] = $is_chasing_playlet;
        $episodes_info["is_likes"] = $is_likes;
        if ($episodes_info["amount"]>0){
            $recd_data["code"] = 20030;
            $recd_data["data"] = [];
        }else{
            $recd_data["code"] = 10000;
            $recd_data["data"] = $episodes_info;
        }

        #is_chasing_playlet
        #is_favorite
        return $recd_data;
    }
    /**
     * 用于获取这短剧的最后一集,redis key 为1天
     * author bobo
     * date 2024-03-29
     */
    public function get_playlet_last_episodes($playlet_id){

        //用于获取这短剧的最后一集
        $redis_key = 'playlet_last_episodes'.$playlet_id;
        $playlet_last_episodes = $this->redisService->get($redis_key);
        if(empty($playlet_last_episodes)){
            $playlet_last_episodes = 0;
            $playlet_data = $this->get_playlet_info($playlet_id);
            if(!empty($playlet_data)){
                $playlet_last_episodes_info = Db::table("playlet_episodes")->where(["playlet_id"=>$playlet_id])->where('status',1)
                    ->orderBy("playlet_number","desc")->select("playlet_number")->first();
                if(!empty($playlet_last_episodes_info)){
                    $playlet_last_episodes = $playlet_last_episodes_info->playlet_number;
                    $this->redisService->set($redis_key,$playlet_last_episodes);
                    $this->redisService->expire($redis_key,86400);
                }
            }
        }
        return $playlet_last_episodes;
    }

    /**
     * 用于获取这推广链接和短剧之间的关系
     * author bobo
     * date 2024-03-20
     */
    public function get_playlet_spread($playlet_id,$spread_id){

        //获取推广链接和短剧之间的关系
        $redis_key = 'playlet_spread'.$playlet_id.$spread_id;
        $playlet_spread_list = $this->redisService->get($redis_key);
        $playlet_spread_list = json_decode($playlet_spread_list,true);
        if(empty($playlet_spread_list)){

            $playlet_spread_list = array();
            //默认播放集数，默认金币价格
            $playlet_number_num = 6;
            $playlet_number_num_pay = 200;
            $we_com_cover = '';
            $playlet_data = $this->get_playlet_info($playlet_id);
            //提审方的AppID
            $applet_data = $this->get_applet_info('10000');
            if(!empty($playlet_data)){
                $main_playlet_id = $playlet_data['main_playlet_id'];
                //获取传过来的短剧的ID,判断是不是主剧ID
                if($main_playlet_id != $playlet_id){
                    $playlet_data = $this->get_playlet_info($main_playlet_id);
                }
                //主剧信息
                if(!empty($playlet_data)){
                    //判断
                    if(!empty($spread_id)) {
                        $data_spread = DB::table('data_spread')->select(['playlet_id','playlet_number_num','playlet_number_num_pay'])->where('id',$spread_id)->first();
                        if(!empty($data_spread->playlet_id) && $data_spread->playlet_id == $playlet_id) {
                            $playlet_number_num = $data_spread->playlet_number_num >=1?$data_spread->playlet_number_num :0;
                            $playlet_number_num_pay = $data_spread->playlet_number_num_pay>0?$data_spread->playlet_number_num_pay:0;
                        }
                        if($data_spread->playlet_id == $playlet_id){
                            $we_com_cover = $playlet_data['we_com_cover'];
                        }
                    }
                    $playlet_spread_list['we_com_cover'] = $we_com_cover;
                    $playlet_spread_list['start_serial_no'] = 1;
                    $playlet_spread_list['end_serial_no'] = $playlet_number_num;
                    $playlet_spread_list['pay_amount'] = $playlet_number_num_pay;
                    $playlet_spread_list['drama_id'] = $playlet_data['drama_id'];
                    $playlet_spread_list['app_id'] = $applet_data['app_id'];
                    $playlet_spread_list['cover'] = $playlet_data['cover'];
                    $playlet_spread_list['playlet_name'] = $playlet_data['name'];
                    $this->redisService->set($redis_key,json_encode($playlet_spread_list));
                    $this->redisService->expire($redis_key,30);
                }
            }
        }
        return $playlet_spread_list;
    }

    /**
     * 用于获取对接新的微信播放器用户购买过的短剧
     * author bobo
     * date 2024-03-20
     */
    public function get_buyPlaySerial_list($applet_id,$user_id,$playlet_id){
        $returnData = [];
        $user_info = $this->userService->user_info($applet_id,$user_id);

        if ($user_info->vip_effective_time > 0){
            $vip_effective_time = strtotime($user_info->vip_effective_time);
        }else{
            $vip_effective_time = 0 ;
        }
        //判断如果用户还是vip的话
        if ($user_info->is_vip and $vip_effective_time>time()) {

            $last_episodes = $this->get_playlet_last_episodes($playlet_id);
            //获取这部剧最后一集
            if(!empty($last_episodes)){
                $returnData[] = [1,$last_episodes];
            }
        }else{
            $buy_episodes = $this->get_my_playlet_episodes($applet_id,$user_id,$playlet_id);

            if(!empty($buy_episodes)){
                sort($buy_episodes);
                $combination_data = [];
                foreach ($buy_episodes as $number) {
                    if (empty($combination_data) || end($combination_data)[1] + 1 != $number) {
                        $combination_data[] = [$number, $number];
                    }else {
                        $push_combination_data = end($combination_data);
                        $push_combination_data[1] = $number;
                        // 获取最后一个子数组的key
                        $lastKey = key($combination_data);
                        $combination_data[$lastKey] = $push_combination_data;
                    }
                }
                foreach ($combination_data as $subArray) {
                    $returnData[] = [$subArray[0], $subArray[1]];
                }
            }
        }
        return $returnData;
    }
    /**
     * 获取字符串前16个字节，不足16个字节后面补零
     * author bobo
     * date 2024-03-20
     */
    function get_16_bytes($str) {
        $len = strlen($str);
        if ($len < 16) {
            $str = str_pad($str, 16, "\0");
        } else if ($len > 16) {
            $str = substr($str, 0, 16);
        }
        return $str;
    }
    /**
     * 加密播放列表
     * author bobo
     * date 2024-03-20
     */
    public function lock_data_req($xc_open_id,$playSerial_list,$buy_playSerial_list,$applet_id){

        $login_info = $this->redisService->hGet('login_info:'.$applet_id,$xc_open_id);
        $login_info = json_decode($login_info,true);

        $session_key = $login_info['session_key'];
        $serial_list = array();
        //start_serial_no	number	剧集编号，表示起始剧集编号，从1开始
        //end_serial_no	    number	结束剧集编号，包含此集
        //status	        number	上面的起始和结束区间内剧集是否可播放。// 1-可播放,2-不可播放


        $serial_list[] = ['start_serial_no' => intval($playSerial_list['start_serial_no']),'end_serial_no' => intval($playSerial_list['end_serial_no']),'status' => 1];
        foreach ($buy_playSerial_list as $value){
            $serial_list[] = ['start_serial_no' => intval($value[0]),'end_serial_no' => intval($value[1]),'status' => 1];
        }
        $encrypt_data = [
            'openid' => $xc_open_id,
            'src_appid' => $playSerial_list['app_id'],
            'drama_id' => strval($playSerial_list['drama_id']),
            'serial_list' => $serial_list,
            'data_expire_at' => time()+7200
        ];
        var_dump($encrypt_data);
        //使用AES-128-ECB算法对data进行加密，密钥是获取的session_key的前16个字节
        $cipher = 'aes-128-ecb';
        $key = $this->get_16_bytes($session_key);
        $plaintext  = json_encode($encrypt_data);
        $length = openssl_cipher_iv_length($cipher);
        // 生成一个伪随机字节串
        if ($length > 0) {
            $iv = openssl_random_pseudo_bytes($length);
        } else {
            $iv = '';
        }
        //加密data
        $ciphertext = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
        //加密后，进行base64编码
        $encodedData = base64_encode($ciphertext);
        $returnData = array();
        $returnData['encryptData'] = $encodedData;
        return $returnData;
    }

    public function get_my_episodes_list($applet_id,$playlet_id,$user_id,$spread_id){
        # 2024-02-23 合并剧集改动
        $merge_main_playlet_id = $this->get_merge_main_playlet_id($playlet_id);
        $merge_main_playlet_id = intval($merge_main_playlet_id);
        if($merge_main_playlet_id) {
            $user_same_main_merge_playlet_id = $this->get_user_same_main_merge_playlet_id($merge_main_playlet_id,$user_id,$applet_id);
            if($user_same_main_merge_playlet_id) {
                $playlet_id  = $user_same_main_merge_playlet_id;
            }
        }
        # 剧集列表
        $episodes_list = $this->episodes_list($playlet_id,$spread_id,$merge_main_playlet_id);

        foreach ($episodes_list as $key=>$value){
            $is_likes = 1;
            $is_chasing_playlet = 1;
            if ($value->playlet_number > 2){
                $is_likes = 0;
                $is_chasing_playlet = 0;
            }
            if ($value->amount > 0){
                $value->pay_staus = 0;
            }else{
                $value->pay_staus = 1;
            }
            $value->is_likes = $is_likes;
            $value->is_chasing_playlet = $is_chasing_playlet;
        }
        if(empty($episodes_list)) {
            $redis_key = 'error_playlet_id'.$applet_id.$playlet_id.$spread_id;
            $error_data = [
                'applet_id'=>$applet_id,
                'playlet_id'=>$playlet_id,
                'user_id'=>$user_id,
                'spread_id'=>$spread_id,
            ];
            $this->redisService->set($redis_key,json_encode($error_data));
        }
        return $episodes_list;
    }

    public function search($applet_id,$kw){
        echo $kw;
        $playlet_ids = $this->get_applet_playlet_rel($applet_id);
        $rec_data = Db::table("playlet")->whereIn("id",$playlet_ids)->where([
            ["status","=",1],
            ["deleted","=",0],
            ["name","like",'%'.$kw.'%']
        ])->select("id as playlet_id","name","tag","cover","last_episode_number","introduction","hot_number")->forPage(1,10)->get();
        foreach ($rec_data as $key =>$val){
            if (!empty($val->cover)){
                $val->cover = $this->get_curl_tool($val->cover);
            }
        }
        return $rec_data;
    }

    public function get_user_likes_playlet($applet_id,$user_id,$page=1){
        # 用户点赞历史
        $list = Db::table("data_user_likes_playlet")->where(["applet_id"=>$applet_id,"user_id"=>$user_id])->select("id","user_id","playlet_id","playlet_number","playlet_number_name")->forPage($page)->orderBy("create_at","desc")->get();
        $list = $this->object_to_array($list);
        foreach ($list as $key=>$value){
            $playlet_info = $this->playlet_info($value["playlet_id"]);
            $list[$key]["playlet_name"] = $playlet_info["name"];
            $list[$key]["cover"] = $playlet_info["cover"];
            $list[$key]["last_episode_number"] =  $playlet_info["last_episode_number"];
        }
        return $list;
    }

    public function chasing_playlet($applet_id,$user_id,$page=1,$playlet_ids=""){
        if ($playlet_ids){
            $playlet_ids = json_decode($playlet_ids, true);
        }else{
            $playlet_ids= [];
        }
        if (empty($playlet_ids)){
            $list = Db::table("data_user_chasing_playlet")->where(["applet_id"=>$applet_id,"user_id"=>$user_id])->select("playlet_id")->forPage($page,50)->orderBy("update_at","desc")->get();
            $list = $this->object_to_array($list);
            foreach ($list as $key=>$value){
                $playlet_info = $this->playlet_info($value["playlet_id"]);
                $list[$key]["playlet_name"] = $playlet_info["name"];
                $list[$key]["cover"] = $playlet_info["cover"];
                $list[$key]["tag"] = $playlet_info["tag"];
                $list[$key]["last_episode_number"] =  $playlet_info["last_episode_number"];
            }
        }else{
            $list = [];
            foreach ($playlet_ids as $key=>$val){
                $playlet_info = $this->playlet_info($val);
                $list[$key]["playlet_id"] =$playlet_info["id"];
                $list[$key]["playlet_name"] = $playlet_info["name"];
                $list[$key]["cover"] = $playlet_info["cover"];
                $list[$key]["tag"] = $playlet_info["tag"];
                $list[$key]["last_episode_number"] =  $playlet_info["last_episode_number"];

            }
        }
        return $list;
    }

    public function playlet_history($applet_id,$user_id,$page=1){
        $list = Db::table("data_user_playlet_history")->where(["applet_id"=>$applet_id])->select("id","user_id","playlet_id","playlet_number","playlet_number_name")->forPage($page)->orderBy("update_at","desc")->get();
        $list = $this->object_to_array($list);
        foreach ($list as $key=>$value){
            $playlet_info = $this->playlet_info($value["playlet_id"]);
            $list[$key]["playlet_name"] = $playlet_info["name"];
            $list[$key]["cover"] = $playlet_info["cover"];
            $list[$key]["tag"] = $playlet_info["tag"];
            $list[$key]["last_episode_number"] =  $playlet_info["last_episode_number"];
        }
        return $list;
    }



    public function get_my_playlet_episodes($applet_id,$user_id,$playlet_id){
        $user_id = (string)$user_id;
        #2024-02-26套娃:合并剧集,所有信息
        $merge_main_playlet_id = $this->get_merge_main_playlet_id($playlet_id);
        $merge_main_playlet_id = intval($merge_main_playlet_id);
        if($merge_main_playlet_id) {
            $user_same_main_merge_playlet_id = $this->get_user_same_main_merge_playlet_id($merge_main_playlet_id,$user_id,$applet_id);
            if($user_same_main_merge_playlet_id) {
                $playlet_id  = $user_same_main_merge_playlet_id;
            }
        }

        $redis_key = "log:playlet:pay:".$applet_id.":".$playlet_id;
        $playlet_log_list = $this->redisService->hGet($redis_key,$user_id);
        $playlet_log_list = json_decode($playlet_log_list,true);
//        $playlet_log_list =[];
        if (empty($playlet_log_list)){
            #购买用户短剧列表
            $playlet_log_list_tmp = Db::table("data_user_pay_playlet_log")->where([
                "applet_id"=>$applet_id,
                "user_id"=>$user_id,
                "playlet_id"=>$playlet_id,
            ])->select("playlet_number")->get();
            $playlet_log_list_tmp = $this->object_to_array($playlet_log_list_tmp);
            if (!empty($playlet_log_list_tmp)){
                foreach ($playlet_log_list_tmp as $key =>$value){
                    $playlet_log_list[$key] = $value['playlet_number'];
                }
                $this->redisService->hSet($redis_key,$user_id,json_encode($playlet_log_list));
            }else{
                $playlet_log_list = [];
            }
        }
        return $playlet_log_list;
    }

    public function up_my_playlet_episodes($applet_id,$user_id,$playlet_id){
        # 更新购买记录
        $user_id = (string)$user_id;
        $redis_key = "log:playlet:pay:".$applet_id.":".$playlet_id;
        $this->redisService->hDel($redis_key,$user_id);
    }

    public function get_user_likes($applet_id,$user_id,$playlet_id){
        $user_id = (string)$user_id;
        $redis_key = "log:playlet:likes:".$applet_id.":".$playlet_id;
        $playlet_log_list = $this->redisService->hGet($redis_key,$user_id);
        $playlet_log_list = json_decode($playlet_log_list,true);
        if (empty($playlet_log_list)){
            #购买用户短剧列表
            $playlet_log_list_tmp = Db::table("data_user_likes_playlet")->where([
                "applet_id"=>$applet_id,
                "user_id"=>$user_id,
                "playlet_id"=>$playlet_id,
            ])->select("playlet_number")->get();
            $playlet_log_list_tmp = $this->object_to_array($playlet_log_list_tmp);
            if (!empty($playlet_log_list_tmp)){
                foreach ($playlet_log_list_tmp as $key =>$value){
                    $playlet_log_list[$key] = $value['playlet_number'];
                }
                $this->redisService->hSet($redis_key,$user_id,json_encode($playlet_log_list));
            }else{
                $playlet_log_list = [];
            }
        }
        return $playlet_log_list;
    }


    public function up_my_likes($applet_id,$user_id,$playlet_id){
        # 更新购买记录
        $user_id = (string)$user_id;
        $redis_key = "log:playlet:likes:".$applet_id.":".$playlet_id;
        $this->redisService->hDel($redis_key,$user_id);
    }

    public function add_likes($applet_id,$user_id,$playlet_id,$playlet_number){
        #点赞
        $likes_ids = $this->get_user_likes($applet_id,$user_id,$playlet_id);
        if (!in_array($playlet_number,$likes_ids)){
            $episodes_info = $this->episodes_info($playlet_id,$playlet_number);
            $playlet_number_name = $episodes_info["playlet_number_name"];
            Db::table("data_user_likes_playlet")->insertGetId(["user_id"=>$user_id,"playlet_id"=>$playlet_id,"playlet_number"=>$playlet_number,"applet_id"=>$applet_id,"playlet_number_name"=>$playlet_number_name]);
            $this->up_my_likes($applet_id,$user_id,$playlet_id);
        }
    }

    public function sync_likes($applet_id,$user_id,$playlet_id,$playlet_numbers){
        Db::table("data_user_likes_playlet")->where([
            "applet_id"=>$applet_id,
            "user_id"=>$user_id,
            "playlet_id"=>$playlet_id,
        ])->delete();
        $add_data = [
            "user_id"=>$user_id,
            "playlet_id"=>$playlet_id,
            "applet_id"=>$applet_id
        ];
        $playlet_numbers = json_decode($playlet_numbers,true);
        print_r($playlet_numbers);
        if ($playlet_numbers){
            foreach ($playlet_numbers as $key=>$val){
                $episodes_info = $this->episodes_info($playlet_id,(string)$val);
                $playlet_number_name = $episodes_info["playlet_number_name"];
                $add_data["playlet_number"] = $val;
                $add_data["playlet_number_name"] = $playlet_number_name;
                Db::table("data_user_likes_playlet")->insertGetId($add_data);
            }
        }
        $this->up_my_likes($applet_id,$user_id,$playlet_id);

    }
    public function del_likes($applet_id,$user_id,$playlet_id,$playlet_number){
        #点赞
        $likes_ids = $this->get_user_likes($applet_id,$user_id,$playlet_id);
        if (in_array($playlet_number,$likes_ids)){
            Db::table("data_user_likes_playlet")->where([
                "applet_id"=>$applet_id,
                "user_id"=>$user_id,
                "playlet_id"=>$playlet_id,
                "playlet_number"=>$playlet_number,
            ])->delete();
            $this->up_my_likes($applet_id,$user_id,$playlet_id);
        }
    }

    public function up_my_chasing($applet_id,$user_id){
        # 更新
        $redis_key = "log:playlet:chasing:".$applet_id;
        $this->redisService->hDel($redis_key,$user_id);
    }
    public function sync_chasing($applet_id,$user_id,$playlet_ids){
        # 同步追剧
        $playlet_ids = json_decode($playlet_ids,true);
        Db::table("data_user_chasing_playlet")->where([
            "user_id"=>$user_id,
            "applet_id"=>$applet_id,
        ])->delete();
        $add_data = [
            "applet_id"=>$applet_id,
            "user_id"=>$user_id,
        ];
        $tmp_inset = [];
        if ($playlet_ids){
            $playlet_ids = $this->array_fast_unique($playlet_ids);
            $tmp = array_reverse($playlet_ids);
            $i = 0;
            foreach ($tmp as $key=>$value){
                $add_data["playlet_id"] = $value;
                $tmp_inset[$i] = $add_data;
                $i ++;
            }
            Db::table("data_user_chasing_playlet")->insert($tmp_inset);
            unset($tmp_inset);unset($add_data);unset($tmp);
        }

        $this->up_my_chasing($applet_id,$user_id);
    }

    public function sync_zl_list($applet_id,$user_id,$sync_data){
        $recommend_list = $this->get_user_recommend($applet_id,$user_id);
        foreach ($recommend_list as $key =>$val){
            $val_tmp["playlet_id"] = $val["playlet_id"];
            $val_tmp["playlet_number"] = $val["episodes_list"]["playlet_number"];
            $val_tmp["playlet_number_name"] = $val["episodes_list"]["playlet_number_name"];
            $val_tmp["is_chasing_playlet"] = !empty(isset($sync_data[$key]["is_chasing_playlet"])) ? $sync_data[$key]["is_chasing_playlet"] : "-1";
            $val_tmp["is_likes"] = !empty(isset($sync_data[$key]["is_likes"]))? $sync_data[$key]["is_likes"] :"-1";
            $val_tmp["user_id"] = $user_id;
            $val_tmp["applet_id"] = $applet_id;
            if ($val_tmp["is_chasing_playlet"] !="-1"){
                $this->sync_find_chasing($val_tmp);
                $this->sync_find_likes($val_tmp);
            }
        }
        unset($recommend_list);
    }

    public function sync_find_chasing($data){
        Db::table("data_user_chasing_playlet")->where([
            "user_id"=>$data["user_id"],
            "applet_id"=>$data["applet_id"],
            "playlet_id"=>$data["playlet_id"],
        ])->delete();
        if ($data["is_chasing_playlet"] == 1)
        {
            unset($data["is_chasing_playlet"]);
            unset($data["playlet_number"]);
            unset($data["is_likes"]);
            unset($data["playlet_number_name"]);
            Db::table("data_user_chasing_playlet")->insertGetId($data);
        }
        $this->up_my_chasing($data["applet_id"],$data["user_id"]);
    }

    public function sync_find_likes($data){
        Db::table("data_user_likes_playlet")->where([
            "user_id"=>$data["user_id"],
            "applet_id"=>$data["applet_id"],
            "playlet_id"=>$data["playlet_id"],
            "playlet_number"=>$data["playlet_number"],
        ])->delete();
        if ($data["is_likes"] == 1)
        {
            unset($data["is_chasing_playlet"]);
            unset($data["is_likes"]);
            Db::table("data_user_likes_playlet")->insertGetId($data);
        }
        $this->up_my_likes($data["applet_id"],$data["user_id"],$data["playlet_id"]);
    }
}